<template>
  <div class="wrapper">
    
    <div>
      <el-card class="card_wrapper">
        
        <div slot="header" >
          <div class="nav">
            <myBreadcrumb :itemlist="itemlist"></myBreadcrumb>
          </div>
          <div class="filter_wapper">
            <el-row>
              <el-col :span="7">
                <el-input @clear="search" placeholder="请输入内容" v-model="pageInfo.query" clearable>
                  <el-button @click="search" slot="append" icon="el-icon-search" ></el-button>
                </el-input>
              </el-col>
              <el-col :span="4">
                <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>

                <!-- 用户新增 Dialog -->
                <el-dialog @close="resetUser('userForm')" title="用户信息" :visible.sync="dialogFormVisible">
                  <el-form :model="userForm" 
                    ref="userForm"
                    :rules="userFormRules">
                    <el-form-item label="Username" prop="username" :label-width="formLabelWidth">
                      <el-input v-model="userForm.username" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="Password" prop="password" :label-width="formLabelWidth">
                      <el-input type="password" v-model="userForm.password"  autocomplete="off" placeholder="please enter password" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="Email" prop="email" :label-width="formLabelWidth">
                      <el-input type="email" v-model="userForm.email" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="Mobilnumber" prop="mobile" :label-width="formLabelWidth">
                      <el-input v-model="userForm.mobile" autocomplete="off"></el-input>
                    </el-form-item>
                  </el-form>
                  <div slot="footer">
                    <el-button @click="resetUser('userForm')">Reset</el-button>
                    <el-button @click="addUser('userForm')" type="primary">Confirm</el-button>
                  </div>
                </el-dialog>
              </el-col>
            </el-row>
            
          </div>
        </div>
        
        <div class="content_warpper">
          <el-table
          :data="tableData"
          style="width: 100%"
          :default-sort = "{prop: 'username', order: 'ascending'}"
          stripe
          >
            <el-table-column type="index"></el-table-column>
            <el-table-column label="姓名" prop="username" sortable></el-table-column>
            <el-table-column label="邮箱" prop="email" sortable></el-table-column>
            <el-table-column label="电话" prop="mobile"></el-table-column>
            <el-table-column label="角色" prop="role_name" sortable></el-table-column>
            <el-table-column label="状态"  sortable>
              <template slot-scope="scope">
                <el-switch
                  @change="handleStateChange(scope.row)"
                  v-model="scope.row.mg_state">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <!-- <template slot-scope="scope"> -->
                <template v-slot="scope">
                <el-button-group>
                  <el-button @click.native.prevent="editRow(scope.$index, tableData, scope.row)" 
                   size="small" 
                   type="primary" 
                   icon="el-icon-edit">
                  </el-button>

                  <!-- 用户编辑 Dialog -->
                <el-dialog @close="resetUser('editForm')" title="修改用户" :visible.sync="editFormVisible">
                  <el-form :model="userForm" 
                    ref="editForm"
                    :rules="userFormRules">
                    <el-form-item label="Username" prop="username" :label-width="formLabelWidth" >
                      <el-input v-model="userForm.username" autocomplete="off" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="Email" prop="email" :label-width="formLabelWidth">
                      <el-input type="email" v-model="userForm.email" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="Mobilnumber" prop="mobile" :label-width="formLabelWidth">
                      <el-input v-model="userForm.mobile" autocomplete="off"></el-input>
                    </el-form-item>
                  </el-form>
                  <div slot="footer">
                    <el-button @click="editFormVisible = false">Cancle</el-button>
                    <el-button @click="updateUser('userForm')" type="primary">Confirm</el-button>
                  </div>
                </el-dialog>

                  <el-button @click.native.prevent="deleteRow(scope.$index, tableData, scope.row)" 
                    size="small" 
                    type="danger" 
                    icon="el-icon-delete"
                    :disabled="scope.row.username === 'admin'">
                  </el-button>
                  <el-tooltip content="分配角色" placement="top" :enterable="false">
                    <el-button @click.native.prevent="shareRoleRow(scope.$index, tableData, scope.row)" 
                      size="small" 
                      type="warning" 
                      icon="el-icon-share">
                    </el-button>
                  </el-tooltip>
                  
                </el-button-group>
              </template>
            </el-table-column>

          </el-table>
        </div>

        <div class="pages_wrapper">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageInfo.pagenum"
            :page-sizes="pageInfo.pageSizes"
            :page-size="pageInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total">
          </el-pagination>
        </div>
        
        
      </el-card>
    </div>
  </div>
</template>

<script>
import myBreadcrumb from "components/nav/myBreadcrumb.vue"
import { 
  getUsers, 
  updateUsersState, 
  addUser, 
  deleteUser, 
  updateUser
  } from "network/user/user.js" 
import { checkEmail, checkPhone } from "common/validation.js" 

export default {
  name: "users",
  data() {
    return {
      itemlist: ['用户管理', '用户列表'],
      pageInfo: {
        total: 0,
        pagenum: 1,
        pagesize: 5,
        pageSizes: [5, 10],
        query: ''
      },
      sourceData: [],
      tableData: [],
      dialogFormVisible: false,
      editFormVisible: false,
      formLabelWidth: '120px',
      userForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
        id: ''
      },
      // 表单验证规则
      userFormRules: {
        username: [
          {required: true,message: 'please enter user name~!', trigger: 'blur'},
          {min: 3, max: 10, message: 'The length is between 3 and 10 characters', trigger: "blur"}
        ],
        password: [
          {
            required: true,
            message: "Please enter the password",
            trigger: "blur",
          }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { validator: checkPhone, trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    myBreadcrumb
  },
  methods: {

    // 分页-选择每页显示条数后处理
    handleSizeChange(val) {
      this.pageInfo.pagesize = val
      this.getUsers()
      console.log(`每页 ${val} 条`);
    },
    // 分页选择不同页面后处理
    handleCurrentChange(val) {
      this.pageInfo.pagenum = val
      this.getUsers()
      console.log(`当前页: ${val}`);
    },
    // 更新用户状态
    handleStateChange(item) {
      this.updateUsersState(item)
    },
    // 查询
    search () {
      // 过滤当前页面显示的内容
      // if(this.query !== '') {
      //   this.tableData = this.sourceData.filter(item => { return item.username.indexOf(this.query) !== -1})
      // } else {
      //   this.tableData = this.sourceData
      // }

      // 去数据库里查询
      this.getUsers();
    },
    // 分配角色
    shareRoleRow(index, rows, row) {

    },
    // 打开修改用户页面
    editRow(index, rows, row) {
      this.editFormVisible = true
      this.userForm = row
    },

    // 更新用户
    async updateUser(formName) {
      let { data, meta } = await updateUser(this.userForm)
      console.log(data);
      if(meta.status !== 200) {
        this.$message.error(meta.msg)
      } else {
        this.$message.success(meta.msg)
      }
      this.editFormVisible = false
      this.getUsers()
    },

    // 删除用户
    deleteRow(index, rows, row) {
      this.$confirm('This action will permanently delete the user. Do you want to continue?', 
      'Tips', 
      {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning',
        showCancelButton: 'true'
      }).then(async () => {
        let res = await deleteUser(row)

        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: 'delete user success~!'
          });
          // rows.splice(index, 1);
          this.getUsers();
        } else {
          this.$message.error(res.meta.msg);
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'cancel delete`!'
        });          
      });
    },
    // 从后台获取用户列表
    async getUsers() {
      let { data, meta } = await getUsers(this.pageInfo);
      this.sourceData = data.users
      this.tableData = this.sourceData
      this.pageInfo.total = data.total
      this.pageInfo.pagenum = data.pagenum
    },
    // 到后台更新用户状态
    async updateUsersState(userInfo) {
      let res = await updateUsersState(userInfo);
      if(res.meta.status !== 200) {
        return this.$message.error('update user status fialled~!')
      }
      this.$message.success('update user status success~!')
    },
    // table 列配置的formatter
    formatter(row, column) {
      return row[column.property];
    },
    // 增加用户
    addUser(formName) {
      this.$refs[formName].validate(async (valid) => {
        if(valid) {
          let res = await addUser(this.userForm);
          if (res.meta.status !== 201) {
            this.$message.error('add new user fialled~!')
          } else {
            this.$message.success('add new user success~!')
            this.dialogFormVisible = false
            this.getUsers();
          }
        }
      })
    },
    // 重置用户form
    resetUser(formName) {
      this.$refs[formName].resetFields();
    }
  },

  // 组件创建后获取用户列表
  created() {
    this.getUsers();
  },
};

</script>

<style lang="less" scoped>

.filter_wapper {
  margin-top: 15px !important;
}

/deep/ .el-card__body {
    padding-top: 0px ;
}

/deep/ .el-table td, /deep/ .el-table th {
  text-align: center;
}
</style>